package cn.xuewei.controller;

import cn.xuewei.mapper.ContentMapper;
import cn.xuewei.mapper.LikeMapper;
import cn.xuewei.pojo.dto.ContentDTO;
import cn.xuewei.pojo.entity.Content;
import cn.xuewei.pojo.entity.UserLike;
import cn.xuewei.pojo.vo.*;
import cn.xuewei.response.ResultVO;
import cn.xuewei.response.StatusCode;
import cn.xuewei.security.CustomUserDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@RestController
@RequestMapping("/v1/contents/")
public class ContentController {
    @Value("${filePath}")
    private String filePath;

    @Autowired
    ContentMapper contentMapper;

    @Autowired
    LikeMapper likeMapper;

    @RequestMapping("add-new")
    public ResultVO addNew(@RequestBody ContentDTO contentDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        Content content = new Content();
        BeanUtils.copyProperties(contentDTO, content);
        if (contentDTO.getId() == null) {
            content.setCreateBy(userDetails.getUserid());
            content.setCreateTime(new Date());
            contentMapper.insert(content);
        } else {
            content.setUpdateTime(new Date());
            content.setUpdateBy(userDetails.getUserid());
            contentMapper.update(content);
        }
        return ResultVO.ok();
    }

    @RequestMapping("/{type}/management")
    public ResultVO management(@PathVariable Integer type,
                               @AuthenticationPrincipal CustomUserDetails userDetails) {
        //判断是否登录
        if (userDetails == null) {
            return new ResultVO(StatusCode.NOT_LOGIN);
        }
        List<ContentManagementVO> list = contentMapper.selectPersonalContent(type, userDetails.getUserid());
        return ResultVO.ok(list);
    }

    @RequestMapping("/{id}/edit")
    public ResultVO getEdit(@PathVariable Long id,@AuthenticationPrincipal CustomUserDetails userDetails) {
        ContentEditVO contentEditVO = contentMapper.selectByIdForEdit(id);
        if (userDetails.getIsAdmin() == 1 || userDetails.getUserid() == contentEditVO.getCreateBy()) {
            return ResultVO.ok(contentEditVO);
        }
        return new ResultVO(StatusCode.FORBIDDEN_ERROR);
    }

    /*还要在评论表删除有关该文章的评论*/
    @RequestMapping("/{id}/delete")
    public ResultVO delete(@PathVariable Long id, @AuthenticationPrincipal CustomUserDetails userDetails) {
        ContentEditVO contentEditVO = contentMapper.selectByIdForEdit(id);
        if (userDetails.getIsAdmin() == 1 || userDetails.getUserid() == contentEditVO.getCreateBy()) {
            new File(filePath + contentEditVO.getImgUrl()).delete();
            if (contentEditVO.getType() == 2) {
                new File(filePath + contentEditVO.getVideoUrl()).delete();
            }
            contentMapper.deleteById(id);
            return ResultVO.ok();
        }
        return new ResultVO(StatusCode.FORBIDDEN_ERROR);
    }
    //通过侧栏分类请求相关内容数据
    @GetMapping("index/{catId}/{subId}")
    public ResultVO index(@PathVariable Long catId,@PathVariable Long subId) {
        if (catId == 1){
            return ResultVO.ok(contentMapper.indexNew(subId));
        }else
            return ResultVO.ok(contentMapper.indexHot(subId));
    }

    @GetMapping("{id}/detail")
    public ResultVO detail(@PathVariable Long id) {
        contentMapper.updateViewCountById(id);
        ContentDetailVO list = contentMapper.detailById(id);
        return ResultVO.ok(list);
    }

    @GetMapping("/{type}/admin")
    public ResultVO admin(@PathVariable Integer type){
        List<ContentAdminVO> list = contentMapper.selectByTypeForAdmin(type);
        return ResultVO.ok(list);
    }


    /**搜索*/
    @RequestMapping("/{categoryId}/{kd}/search")
    public ResultVO search(@PathVariable Long categoryId,
                          @PathVariable String kd){
        if(categoryId == 0){
            List<ContentSearchVO> list1 = contentMapper.selectByCategoryIdAndKdVideo(categoryId,kd);
            List<ContentSearchVO> list2 = contentMapper.selectByCategoryIdAndKdUser(categoryId,kd);
            List<ContentSearchVO> list3 = contentMapper.selectByCategoryIdAndKdArticle(categoryId,kd);
            List<ContentSearchVO> resultList = Stream.concat(Stream.concat(list1.stream(), list2.stream()), list3.stream())
                    .collect(Collectors.toList());
            return ResultVO.ok(resultList);
        }else if(categoryId == 5|| categoryId == 6){
            List<ContentSearchVO> list = contentMapper.selectByCategoryIdAndKdVideo(categoryId,kd);
            return ResultVO.ok(list);
        }else if(categoryId == 8){
            List<ContentSearchVO> list = contentMapper.selectByCategoryIdAndKdUser(categoryId,kd);
            return ResultVO.ok(list);
        }else if(categoryId == 2 || categoryId == 3){
            List<ContentSearchVO> list2 = contentMapper.selectByCategoryIdAndKdArticle(categoryId,kd);
            List<ContentSearchVO> list1 = contentMapper.selectByCategoryIdAndKdVideo(categoryId,kd);
            List<ContentSearchVO> resultList = Stream.concat(list1.stream(), list2.stream())
                    .collect(Collectors.toList());
            return ResultVO.ok(resultList);
        }else{
            List<ContentSearchVO> list = contentMapper.selectByCategoryIdAndKdArticle(categoryId,kd);
            return ResultVO.ok(list);
        }
    }
    @RequestMapping("/{userId}/searchUser")
    public ResultVO searchUser(@PathVariable Long userId){
        List<ContentSearchVO> list = contentMapper.selectByUserId(userId);
        return ResultVO.ok(list);
    }

    @RequestMapping("/{userId}/searchAll")
    public ResultVO searchAll(@PathVariable Long userId){
        List<ContentSearchVO> list = contentMapper.selectAllByUserId(userId);
        return ResultVO.ok(list);
    }


    /**
     * 获取详情页用户的其他文章Personal homepage
     */
    @RequestMapping("/{userId}/others")
    public ResultVO others(@PathVariable Long userId) {
        List<ContentSimpleVO> list = contentMapper.selectOthersByUserId(userId);
        return ResultVO.ok(list);
    }

    @RequestMapping("/hot")
    public ResultVO hot() {
        List<ContentSimpleVO> list = contentMapper.selectHot();
        return ResultVO.ok(list);
    }

    /**
     * 进入详情页显示用户的总文章数,总视频数和总获赞数
     */
    @GetMapping("{id}/countByUser")
    public ResultVO countByUser(@PathVariable Long id){
        return ResultVO.ok(contentMapper.getCountByUser(id));
    }

    @GetMapping("/courseindex/{paid}/{categoryId}")
    public ResultVO videoindex(@PathVariable int paid,@PathVariable int categoryId){
        List<CourseContentVO> list = contentMapper.selectByVideoCategoryId(categoryId,paid);
        return ResultVO.ok(list);
    }
    @GetMapping("/paidcourseindex/{paid}/{categoryId}")
    public ResultVO courseindex(@PathVariable int categoryId,@PathVariable int paid){
        List<CourseContentVO> list = contentMapper.selectByCourseCategoryId(categoryId,paid);
        return ResultVO.ok(list);
    }
    @RequestMapping("/{contentId}/like")
    public ResultVO like(@AuthenticationPrincipal CustomUserDetails userDetails,@PathVariable Long contentId){
        LikeSimpleVO likeSimpleVO = likeMapper.findByUserIdAndContentId(userDetails.getUserid(),contentId);
        if (likeSimpleVO == null){
            UserLike userLike = new UserLike();
            userLike.setUserId(userDetails.getUserid());
            userLike.setContentId(contentId);
            userLike.setCreateTime(new Date());
            likeMapper.insert(userLike);
            contentMapper.incrementLikeCount(contentId);
            return ResultVO.ok();
        }else {
            likeMapper.delete(userDetails.getUserid(),contentId);
            contentMapper.decrementLikeCount(contentId);
            return new ResultVO(StatusCode.LIKE_FAILED);
        }
    }

    @GetMapping("courselist/{paid}")
    public ResultVO courselist(@PathVariable int paid){
        List<CourseContentVO> list = contentMapper.selectByCourseListId(paid);
        return ResultVO.ok(list);
    }

    @GetMapping("userinfo")
    public ResultVO userInfo(){
        return ResultVO.ok(contentMapper.listByUser());
    }

}
